package com.wg.androidsdk;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import android.util.Log;

public class Ble {

    BluetoothAdapter bluetoothAdapter;
    ScanListener scanListener;

    public Ble(){
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    }

    public void setScanListener(ScanListener listener){
        scanListener = listener;
    }

    /***
     * 打开蓝牙
     */
    public void openBle(){
        if (!bluetoothAdapter.isEnabled()){
            bluetoothAdapter.enable();
        }
    }

    /***
     * 开始扫描
     */
    public void startScan(){
        Log.d("startScan: ","开始扫描" );
        bluetoothAdapter.startLeScan(scanCallback);
        //扫描10s后停止扫描
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                bluetoothAdapter.stopLeScan(scanCallback);
            }
        },10000);

    }

    /***
     * 蓝牙扫描回调
     */
    private BluetoothAdapter.LeScanCallback scanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
             scanListener.OnScanResult(device,rssi);
            Log.d("onLeScan:", device.getName()+" "+device.getAddress());
        }
    };

    /**
     * unity端扫描回调
     */
    public void UnityScanCallBack(String name,String address){
        Log.d("UnityScanCallBack: ", name+" "+address);
    }

}
